package com.beijing.demo.listnode;

/**
 * 曹旭
 * 2025/4/27
 * 合并两个有序链表
 * 力扣连接:
 * https://leetcode.cn/problems/merge-two-sorted-lists/?envType=problem-list-v2&envId=linked-list
 */
public class MergeListNode {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null || list2 == null){
            return list1 == null ? list2 : list1;
        }
        ListNode head = list1.val > list2.val ? list2 : list1;
        ListNode pre = head;
        ListNode cur1 = head.next;
        ListNode cur2 = head == list1 ? list2 : list1;
        while(cur1 != null && cur2 != null){
            if(cur1.val > cur2.val){
                pre.next = cur2;
                cur2 = cur2.next;
            }else {
                pre.next = cur1;
                cur1 = cur1.next;
            }
            pre = pre.next;
        }
        if(cur1 != null || cur2 != null){
            pre.next = cur1 != null ? cur1 : cur2;
        }
        return head;
    }
}
